const { Role } = require('../../model');
const { Op } = require('sequelize'); // sequelize 操作函数

module.exports = {
  // 添加角色
  add: async (req, res) => {
    const { label, desc, menu = '' } = req.body;

    try {
      const role = await Role.create({
        label,
        desc,
        menu,
      });
      if (role) {
        res.send({ errcode: 0, msg: '成功', success: true });
      } else {
        res.send({ errcode: 1, msg: '失败', success: false });
      }
    } catch (error) {
      res.send({ errcode: 1, msg: '失败：' + error, success: false });
    }
  },
  // 获取角色列表
  list: async (req, res) => {
    // 获取列表
    try {
      const role = await Role.findAndCountAll({
        description: ['id', 'label', 'desc', 'menu'],
        where: {
          // id 不为1
          id: {
            //
            [Op.ne]: 1, // 转为sql 为 where id != 1
          },
        },
      });
      if (role) {
        res.send({ errcode: 0, msg: '成功', success: true, data: role });
      } else {
        res.send({ errcode: 1, msg: '失败', success: false });
      }
    } catch (error) {
      res.send({ errcode: 1, msg: '失败: ' + error, success: false });
    }
  },

  // 编辑角色
  edit: async (req, res) => {
    try {
      const { label, desc, menu = '', id } = req.body;
      console.log({ label, desc, menu });
      const role = await Role.update({ label, desc, menu }, { where: { id } });
      if (role) {
        res.send({ errcode: 0, msg: '成功', success: true });
      } else {
        res.send({ errcode: 1, msg: '失败', success: false });
      }
    } catch (error) {
      res.send({ errcode: 1, msg: '失败: ' + error, success: false });
    }
  },
  //   删除角色
  del: async (req, res) => {
    try {
      const { id } = req.body;
      if (id - 0 === 1) {
        res.send({ errcode: 1, msg: '失败 ' + '无权限', success: false });
      }

      const result = await Role.destroy({ where: { id } });
      if (result > 0) {
        res.send({ errcode: 0, msg: '成功', success: true });
      } else {
        res.send({ errcode: 1, msg: '失败', success: false });
      }
    } catch (error) {
      res.send({ errcode: 1, msg: '失败 ' + error, success: false });
    }
  },
};
